package com.syc.mybatis.utils;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {

	private static SqlSessionFactory factory;
	//本地线程,就可以很好的解决线程安全问题.
	//ThreadLocal的主要方法:get(),set(),remove()
	private static ThreadLocal<SqlSession> locals=new ThreadLocal<SqlSession>();
	
	static {
		Reader reader = null;
		try {
			reader = Resources.getResourceAsReader("mybatis.xml");
			//构建SqlSessionFactory对象
			factory = new SqlSessionFactoryBuilder().build(reader);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	//获取SqlSession对象
	public static SqlSession getSqlSession(){
		
		//从本地线程中获取sqlSession对象
		SqlSession sqlSession = locals.get();
		
		if(sqlSession==null){
			//只有本地线程中的sqlSession对象为空的情况下,我们采取开启一个新的sqlSession对象
			sqlSession = factory.openSession();
			//将sqlSession存放进ThreadLocal中
			locals.set(sqlSession);
		}
		
		return sqlSession;
	}
	
	//关闭sqlSession对象
	public static void closeSqlSession(){
		SqlSession sqlSession = locals.get();
		if(sqlSession!=null){
			sqlSession.close();
			//将sqlSession对象从本地线程中脱离
			locals.remove();
		}
	}

}
